<template>
  <el-form label-width="80px">
    <el-form-item label="SPU名称">
      <el-input placeholder="SPU名称" v-model="spuInfo.spuName"></el-input>
    </el-form-item>
    <el-form-item label="品牌">
      <el-select placeholder="请选择" v-model="(spuInfo.tmId as number)">
        <el-option
          v-for="tm in tmList"
          :key="tm.id"
          :value="tm.id"
          :label="tm.tmName"
        />
      </el-select>
    </el-form-item>
    <el-form-item label="SPU描述">
      <el-input
        type="textarea"
        placeholder="SPU名称"
        rows="4"
        v-model="spuInfo.description"
      ></el-input>
    </el-form-item>
    <el-form-item label="SPU图片">
      <el-upload
        v-model:file-list="spuImageList as UploadUserFile[]"
        :action="`${baseUrl}/admin/product/upload`"
        list-type="picture-card"
        :on-preview="handlePictureCardPreview"
        :on-remove="handleRemove"
      >
        <el-icon><Plus /></el-icon>
      </el-upload>

      <el-dialog v-model="dialogVisible">
        <img w-full :src="dialogImageUrl" alt="Preview Image" />
      </el-dialog>
    </el-form-item>

    <el-form-item label="销售属性">
      <el-select
        :placeholder="`还有${unUsedSaleAttrList.length}个未选`"
        v-model="tempSaleAttr"
      >
        <el-option
          v-for="attr in unUsedSaleAttrList"
          :key="attr.id"
          :value="`${attr.id}:${attr.name}`"
          :label="attr.name"
        />
      </el-select>
      <el-button
        type="primary"
        size="default"
        icon="ele-Plus"
        @click="addSaleAttr"
        :disabled="!tempSaleAttr"
        >添加销售属性</el-button
      >
    </el-form-item>
    <el-form-item>
      <el-table :data="spuSaleAttrList" border stripe>
        <el-table-column type="index" width="50" label="序号" />
        <el-table-column label="属性名" prop="saleAttrName"></el-table-column>
        <el-table-column label="属性值名称列表">
          <template v-slot="{ row }">
            <el-tag
              v-for="(tag, index) in row.spuSaleAttrValueList"
              :key="tag.id"
              class="mx-1"
              closable
              :disable-transitions="false"
              @close="row.spuSaleAttrValueList.splice(index, 1)"
            >
              {{ tag.saleAttrValueName }}
            </el-tag>
            <!-- @keyup.enter="handleInputConfirm"
            @blur="handleInputConfirm" -->
            <el-input
              ref="editEle"
              v-if="row.isEdit"
              class="ml-1 w-20"
              size="small"
              v-model="row.inputValue"
              @blur="handleInputConfirm(row, $event)"
            />
            <el-button
              @click="changeToEdit(row)"
              class="button-new-tag ml-1"
              size="small"
              v-else
            >
              + 新增属性值
            </el-button>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template v-slot="{ row, $index }">
            <el-button
              type="danger"
              size="small"
              icon="ele-Delete"
              @click="spuSaleAttrList.splice($index, 1)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" size="default" @click="save">保存</el-button>
      <el-button type="default" size="default" @click="emit('setState', 0)"
        >取消</el-button
      >
    </el-form-item>
  </el-form>
</template>

<script lang="ts">
import { defineComponent } from "vue";

export default defineComponent({
  name: "SpuForm",
});
</script>

<script setup lang="ts">
import { ref, onMounted, computed, nextTick } from "vue";
import { Plus } from "@element-plus/icons-vue";
import {
  requestBaseSaleAttrList,
  requestSaveSpuInfo,
  requestSpuImgList,
  requestSpuSaleAttrList,
  requestUpdateSpuInfo,
} from "@/api/spu";
import type{
  BaseSaleAttrListType,
  SpuImgListType,
  SpuInfoType,
  SpuSaleAttrItemType,
  SpuSaleAttrListType
}from "@/api/spu";
import { ElMessage,} from "element-plus";
import type{UploadProps,UploadUserFile}from "element-plus";
import { requestAllTmList } from "@/api/trademark";
import type {TmListType} from "@/api/trademark";
const baseUrl = import.meta.env.VITE_API_URL;
//1.接受props传值
const props = defineProps<{
  spuInfo: SpuInfoType;
}>();

//2.接受自定义事件,用来切换组件
const emit = defineEmits<{
  (event: "setState", state: number, row?: SpuInfoType): void;
}>();

//3.Spu照片墙的逻辑
//删除原来照片墙的数据,使用我们获取的spuImageList来替代
/* const fileList = ref<UploadUserFile[]>([
  {
    name: "food.jpeg",
    url: "https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100",
  },
  {
    name: "food.jpeg",
    url: "https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100",
  },
]); */

const dialogImageUrl = ref("");
const dialogVisible = ref(false);

const handleRemove: UploadProps["onRemove"] = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles);
};

const handlePictureCardPreview: UploadProps["onPreview"] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!;
  dialogVisible.value = true;
};

//3.根据新增还是修改去请求当前Form需要的数据(其中新增需要发送:1.品牌列表2.所有销售属性列表,修改需要发送:1.品牌列表2.所有销售属性列表3.当前spu图片列表4.当前spu的属性列表)
//声明一些数据 保存品牌列表 所有销售属性列表,当前spu图片列表,当前spu的属性列表
const tmList = ref<TmListType[]>([]);
const saleAttrList = ref<BaseSaleAttrListType>([]);
const spuImageList = ref<SpuImgListType>([]);
const spuSaleAttrList = ref<SpuSaleAttrListType>([]);

const getAllUseData = async () => {
  if (!props.spuInfo.id) {
    try {
      //新增逻辑,发送两个请求
      const result1 = await requestAllTmList();
      tmList.value = result1;
      const result2 = await requestBaseSaleAttrList();
      saleAttrList.value = result2;
    } catch (e) {
      ElMessage.error("品牌请求或者属性列表请求失败");
    }
  } else {
    //修改逻辑,发送四个请求
    const promise1 = requestAllTmList();
    const promise2 = requestBaseSaleAttrList();
    const promise3 = requestSpuImgList(props.spuInfo.id);
    const promise4 = requestSpuSaleAttrList(props.spuInfo.id);

    try {
      const result = await Promise.all([
        promise1,
        promise2,
        promise3,
        promise4,
      ]);
      tmList.value = result[0];
      saleAttrList.value = result[1];

      spuImageList.value = result[2];
      //4.处理照片墙数据(必须书写在有数据的时候再处理数据)
      spuImageList.value.forEach((item) => {
        item.name = item.imgName;
        item.url = item.imgUrl;
      });
      spuSaleAttrList.value = result[3];
      //给spu的销售属性列表的每一项添加一个isEdit属性,代表当前内部的属性值是添加模式还是编辑模式
      spuSaleAttrList.value.forEach((item) => {
        //保存当前销售属性列表中的模式是否是编辑模式
        item.isEdit = false;
        //保存当前销售属性列表中 在编辑模式下输入的内容
        item.inputValue = "";
      });
    } catch (e) {
      ElMessage.error("初始请求失败");
    }
  }
};
//获取所有初始化数据
onMounted(() => {
  getAllUseData();
});

//计算属性计算没有使用的销售属性列表
const unUsedSaleAttrList = computed(() => {
  //处理处理,删除当前spu已经拥有的销售属性
  return saleAttrList.value.filter((item1) => {
    //我们给你一个销售属性对象,我想判断当前的spu销售属性列表里有没有和我一样的,如果没有则返回true,如果有则返回false
    return spuSaleAttrList.value.every((item2) => {
      return item2.saleAttrName !== item1.name;
    });
  });
});

//定义一个数据 收集用户临时选择的销售属性
const tempSaleAttr = ref("");
//添加销售属性值事件
const addSaleAttr = () => {
  const [baseSaleAttrId, saleAttrName] = tempSaleAttr.value.split(":");
  //我们要把数据插入到spuSaleAttrList,所以我们要拼接一个类似的数据格式才能插入
  const tempSpuSaleAttr = {
    baseSaleAttrId: +baseSaleAttrId,
    saleAttrName: saleAttrName,
    spuSaleAttrValueList: [],
  };

  //插入数据到spuSaleAttrList
  spuSaleAttrList.value.push(tempSpuSaleAttr);

  //清空临时数据
  tempSaleAttr.value = "";
};

//保存当前的处在编辑模式的表单元素
const editEle = ref<HTMLInputElement>();
//切换编辑模式的事件函数
const changeToEdit = (row: SpuSaleAttrItemType) => {
  //切换模式
  row.isEdit = true;
  //自动获取焦点
  nextTick(() => {
    editEle.value?.focus();
  });
};

//编辑框失去焦点的事件回调函数
const handleInputConfirm = (row: SpuSaleAttrItemType, e: Event) => {
  //获取当前输入的内容
  let inputValue = row.inputValue as string;
  //判断当前的内容是否为空
  if (!inputValue.trim()) {
    row.isEdit = false;
    ElMessage.error("添加的属性值为空");
    return;
  }

  //判断输入的内容是否有重复
  const isRepeat = row.spuSaleAttrValueList.some((item) => {
    return item.saleAttrValueName === inputValue;
  });

  if (isRepeat) {
    ElMessage.error("添加的属性值有重复");
    row.isEdit = false;
    row.inputValue = "";
    return;
  }

  //把值添加到列表
  //整理以下要添加到row的属性值列表中的数据
  const newSaleAttrValue = {
    //当前所在的销售属性，对应的销售属性id
    baseSaleAttrId: row.baseSaleAttrId,
    //当前销售属性的值
    saleAttrValueName: row.inputValue as string,
    //其他值都不需要，可以不填
  };

  row.spuSaleAttrValueList.push(newSaleAttrValue);

  //最后要清空并切换到按钮模式
  row.isEdit = false;
  row.inputValue = "";
};

const save = async () => {
  //整理 spuImageList 数据
  const newSpuImageList = spuImageList.value.map((item) => {
    // let obj = {};
    if (item.response) {
      return {
        imgUrl: item.response.data as string,
        imgName: item.name as string,
      };
    } else {
      return {
        imgName: item.imgName,
        imgUrl: item.imgUrl,
      };
    }
    // return obj;
  });
  console.log(spuImageList.value);

  //整理SaleAttrvalueList数据，因为里边多了isEdit 和 inputValue两个属性
  spuSaleAttrList.value.forEach((item) => {
    delete item.isEdit;
    delete item.inputValue;
  });

  //把上边整理的两个值添加到spuInfo上
  props.spuInfo.spuSaleAttrList = spuSaleAttrList.value;
  props.spuInfo.spuImageList = newSpuImageList;

  //提交数据
  try {
    if (props.spuInfo.id) {
      //更新操作
      await requestUpdateSpuInfo(props.spuInfo);
    } else {
      //新增操作
      await requestSaveSpuInfo(props.spuInfo);
    }
  } catch (e) {
    ElMessage.error("新增或者更新数据失败");
  }

  //回到列表页
  emit("setState", 0);
};
</script>
